package cn.com.ddapp.ddm.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.com.ddapp.ddm.AppConfig;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.adapter.ClassifyGoodAdpter;
import cn.com.ddapp.ddm.adapter.ClassifyGoodLandAdpter;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.base.BaseApplication;
import cn.com.ddapp.ddm.bean.ClassifyGoodBean;
import cn.com.ddapp.ddm.fragment.base.FitrerFragment;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.ui.empty.EmptyLayout;
import cn.com.ddapp.ddm.util.SPUtils;
import cn.com.ddapp.ddm.util.TDevice;
import cn.com.ddapp.ddm.widget.pulltorefresh.PullToRefreshLayout;
import cn.com.ddapp.ddm.widget.pulltorefresh.pullableview.PullableGridView;
import okhttp3.Call;


/**
 * Created by Administrator on 2016/7/29 0029.
 * 竖屏商品分类
 */
public class GoodClassifyActivity extends FragmentActivity {

	@BindView(R.id.clssify_search)
	EditText clssify_search;
	@BindView(R.id.classify_moren)
	TextView classify_moren;
	@BindView(R.id.classify_sold)
	TextView classify_sold;
	@BindView(R.id.classify_area)
	TextView classify_area;
	@BindView(R.id.classify_more)
	TextView classify_more;
	@BindView(R.id.clssify_refresh)
	PullToRefreshLayout clssify_refresh;
	@BindView(R.id.clssify_list)
	PullableGridView clssify_list;
	@BindView(R.id.empty)
	EmptyLayout emptyLayout;
	@BindView(R.id.back)
	ImageView back;
	@BindView(R.id.fragment_container)
	FrameLayout fragment_container;
	@BindView(R.id.drawer_layout)
	DrawerLayout drawer_layout;
	@BindView(R.id.drawer_content)
	RelativeLayout drawer_content;
    @BindView(R.id.titletext)
    TextView titletext;
	private ClassifyGoodAdpter cAdapter;
	private ClassifyGoodLandAdpter landcAdapter;
	private List<ClassifyGoodBean.ClassifyGood> nList;
	private int st;
	private int addrId;
	private Context context;
	private boolean isCheck=false;
	private int state=0;
//	private SlidingMenu slidingMenu;
    Unbinder unbinder;
	private String result="";
	protected Gson gson = new Gson();
	private int brandId,promotionId;
	private String lId,claName,classiftId;
    private BrandBroact bBrocast=new BrandBroact();
    private String paramIds;
	public static void startIntent(Context context){
		Intent intent=new Intent(context,GoodClassifyActivity.class);
		context.startActivity(intent);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_goodclassify);
        if(TDevice.isTablet(getApplicationContext())){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 横屏
        }else{
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        }
		unbinder= ButterKnife.bind(this);
		classiftId=getIntent().getStringExtra("classiftId");  //分类的ID
        claName=getIntent().getStringExtra("claName");      //分类的昵称
        promotionId=getIntent().getIntExtra("promotionId",1);      //更多特色专享
        titletext.setText(claName);
        brandId=getIntent().getIntExtra("brandId",0);           //品牌的ID
        Log.i("aaa","classiftId--"+classiftId);
		initView();
        initBroast();
	}
    private void initBroast() {
        IntentFilter filter=new IntentFilter();
        filter.addAction("bbId");
        registerReceiver(bBrocast,filter);

    }
    private class BrandBroact extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("bbId")){
                String bId=intent.getStringExtra("bbId");
                paramIds=bId;
                if(!TextUtils.isEmpty(bId)){
                    reequestData(0,0,0,result,lId,brandId,bId);
                }else{
                    reequestData(0,0,0,result,lId,brandId,paramIds);
                }
            }
        }
    }
	public void initView() {
		addrId=getIntent().getIntExtra("addrId",1);
		result=getIntent().getStringExtra("searchResult");
		Log.i("huaG","searchname = "+result);
		lId= SPUtils.getStringData(getApplicationContext(),SPUtils.LID);
		context=getApplicationContext();
		reequestData(0,0,0,result,classiftId,brandId,paramIds);
		clssify_refresh.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
			@Override
			public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
				reequestData(0,0,0,result,classiftId,brandId,paramIds);
				clssify_refresh.refreshFinish(PullToRefreshLayout.SUCCEED);
				st=0;
			}

			@Override
			public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
				st=st+10;
				if(state==0){
					reequestMoreData(st,0,0,result,lId,brandId);
				}else if(state==1){
					reequestMoreData(st,1,1,result,lId,brandId);
				}else if(state==2){
					reequestMoreData(st,0,1,result,lId,brandId);
				}else if(state==4){
					reequestMoreData(st,0,0,result,lId,brandId);
				}

			}
		});
		getSupportFragmentManager().beginTransaction().replace(R.id.drawer_content, new FitrerFragment()).commit();
	}

	private void reequestMoreData(final int a,final int sort,final int sortype,final String name,final String leveid,final int brandId) {
		emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
		final OkUtilCallback okUtilCallback = new OkUtilCallback(emptyLayout) {
			@Override
			public void onMyResponse(String response, int id) {
				ClassifyGoodBean entity = gson.fromJson(response, ClassifyGoodBean.class);
				if ((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))) {
					BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
				}else{
					List<ClassifyGoodBean.ClassifyGood> ll=entity.getList();
					if(ll.size()>0){
						cAdapter.addView(ll);
						clssify_refresh.refreshFinish(PullToRefreshLayout.SUCCEED);
						st=a;
					}else{
						clssify_refresh.loadmoreFinish(PullToRefreshLayout.NODATA);
					}

				}
			}

            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
            }
        };
		String params="";
        if(TextUtils.isEmpty(name) && brandId==0){
            params="addrId="+AppConfig.CITY_ID+"&sortLevel="+leveid+"&st="+a+"&sort="+sort+"&sortType="+sortype;
        }
		if(TextUtils.isEmpty(name) && brandId!=0){
			params="addrId="+AppConfig.CITY_ID+"&sortLevel="+leveid+"&st="+a+"&sort="+sort+"&sortType="+sortype+"&brandId="+brandId;
		} if(brandId !=0 && TextUtils.isEmpty(name)){
            params="addrId="+AppConfig.CITY_ID+"&st="+a+"&sort="+sort+"&sortType="+sortype+"&brandId="+brandId;
        }
        if(!TextUtils.isEmpty(name) ){
			params="addrId="+AppConfig.CITY_ID+"&sortLevel="+leveid+"&st="+a+"&sort="+sort+"&sortType="+sortype+"&key="+name;
		}
		OKUtilAPI.post(OKUtilAPI.goodclassify, params, okUtilCallback);
	}

	private void reequestData(final int a,final int sort,final int sortype,final String name,final String leveid,final int brandId,final String paramIds) {
		emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
		final OkUtilCallback okUtilCallback = new OkUtilCallback(emptyLayout) {
			@Override
			public void onMyResponse(String response, int id) {
				ClassifyGoodBean entity = gson.fromJson(response, ClassifyGoodBean.class);
				if ((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))) {
					emptyLayout.setErrorType(EmptyLayout.NODATA);
					BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
				}else if(entity.getResult().equals("OK") && entity.getList().size()==0){
					emptyLayout.setErrorType(EmptyLayout.NODATA);
				}else{
					nList=entity.getList();
					cAdapter=new ClassifyGoodAdpter(context,nList);
					clssify_list.setAdapter(cAdapter);
					clssify_list.setNumColumns(2);
					clssify_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
							Intent intent = new Intent(getApplicationContext(), CommidContentActivity.class);
							int id = nList.get(i).getId();
							Log.e("IDS", "ID===========" + id);
							intent.putExtra("type","id");
							intent.putExtra("id", String.valueOf(id));
							startActivity(intent);
						}
					});
				}
			}

			@Override
			public void onError(Call call, Exception e, int id) {
				super.onError(call, e, id);
				emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
			}
		};
		String params="";
		if(promotionId!=1){
			params="addrId="+AppConfig.CITY_ID+"&st="+a+"&sort="+sort+"&sortType="+sortype+"&promotionId="+promotionId;
		}else{
			if(TextUtils.isEmpty(name) && brandId==0){
				params="addrId="+AppConfig.CITY_ID+"&sortLevel="+leveid+"&st="+a+"&sort="+sort+"&sortType="+sortype;
			}
			if(TextUtils.isEmpty(name) && brandId!=0){
				params="addrId="+AppConfig.CITY_ID+"&sortLevel="+leveid+"&st="+a+"&sort="+sort+"&sortType="+sortype+"&brandId="+brandId;
			} if(brandId !=0 && TextUtils.isEmpty(name)){
				params="addrId="+AppConfig.CITY_ID+"&st="+a+"&sort="+sort+"&sortType="+sortype+"&brandId="+brandId;
			}
			if(!TextUtils.isEmpty(name) ){
				params="addrId="+AppConfig.CITY_ID+"&st="+a+"&sort="+sort+"&sortType="+sortype+"&key="+name;
			}
			if(TextUtils.isEmpty(name) && brandId==0 && !TextUtils.isEmpty(paramIds)){
				params="addrId="+AppConfig.CITY_ID+"&sortLevel="+leveid+"&st="+a+"&sort="+sort+"&sortType="+sortype+"&paramIds="+paramIds;
			}
		}

		OKUtilAPI.post(OKUtilAPI.goodclassify, params, okUtilCallback);
	}

	/**
	 * sort int[N]  排序 0: 价格，1:销量 默认价格
	 sortType int[N] 0:升序 1:降序 默认升序
	 sortLevel String[N] 分类级别ID
	 st int[N] 开始读取的行  默认0
	 * @param v
     */
	@OnClick({R.id.back,R.id.img_error_layout,R.id.classify_moren,R.id.classify_sold,R.id.classify_area,R.id.classify_more,R.id.clssify_search})
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
			case R.id.back:
				finish();
				break;
			case R.id.img_error_layout:
					reequestData(0,0,0,"",classiftId,brandId,paramIds);
				break;
			case R.id.classify_moren:
				setTextCurColor(classify_moren);
				setTextResetColor(classify_sold);
				setTextResetColor(classify_area);
				state=0;
				isCheck=false;
				setTextImage(R.mipmap.arrow_down);
					reequestData(0,0,0,result,lId,brandId,paramIds);
				break;
			case R.id.classify_sold:
				setTextCurColor(classify_sold);
				setTextResetColor(classify_moren);
				setTextResetColor(classify_area);
				state=1;
				isCheck=false;
				setTextImage(R.mipmap.arrow_down);
					reequestData(0,1,1,result,lId,brandId,paramIds);
				break;
			case R.id.classify_area:
				setTextCurColor(classify_area);
				setTextResetColor(classify_moren);
				setTextResetColor(classify_sold);
					if(isCheck){
						state=2;
						isCheck=false;
						setTextImage(R.mipmap.arrow_d);
						reequestData(0,0,1,result,lId,brandId,paramIds);
					}else{
						state=4;
						isCheck=true;
						setTextImage(R.mipmap.arrow_u);
						reequestData(0,0,0,result,lId,brandId,paramIds);
					}
				break;
			case R.id.classify_more:
				state=3;
				drawer_layout.openDrawer(drawer_content);
				break;
			case R.id.clssify_search:
				intent=new Intent(context,SearchActivity.class);
				startActivity(intent);
				break;

		}
	}
	private void setTextImage(int resId){
		Drawable dw=getResources().getDrawable(resId);
		dw.setBounds(0,0,dw.getMinimumWidth(),dw.getMinimumHeight());
		classify_area.setCompoundDrawables(null,null,dw,null);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unbinder.unbind();
        unregisterReceiver(bBrocast);
	}

	public void setTextCurColor(TextView tv){
		tv.setTextColor(context.getResources().getColor(R.color.color_orange));
	}
	public void setTextResetColor(TextView tv){
		tv.setTextColor(context.getResources().getColor(R.color.text_color_greyer));
	}
}
